import Cookie from 'js-cookie'
import * as types from '../constants/ActionTypes'
import { requestBaseUrl } from '../constants/AjaxConfig'

// asynchronous action creators
export const requestLogin = () => ({type: types.REQUEST_LOGIN})
export const receiveLogin = (username, key, error) => (
    {type: types.RECEIVE_LOGIN, username, key, error}
)

export const logout = (error) => ({type: types.LOGOUT, error})
export const profileUpdated = (newProfile, error) => ({ type: types.NEWPROFILE, error, newProfile})
export const pageChange = () => ({type: types.PAGE_CHANGE})
export const registerInProcess = (error) => ({ type: types.REGISTER_INPROCESS, error })
export const activateInProcess = (error) => ({ type: types.ACTIVATE_INPROCESS, error })
const LOGIN_URL = requestBaseUrl + 'rest-auth/login/'
const processResponse = response => {
    if(response.ok)
        return null
    else{
        return response.json()
    }
}
export const makeLogin = (username, password) => {
    return function(dispatch) {
        dispatch(requestLogin())
        let submitStr = JSON.stringify({username, password});
        let loginConfig =  {
            body: submitStr,
            headers: {
                "Content-Type": "application/json",                  
            },
            method: 'POST',
            credentials: 'include'
        }
        let csrftoken = Cookie.get('csrftoken')
        if (csrftoken)
            loginConfig.headers['X-CSRFToken'] = csrftoken
        
        return fetch(LOGIN_URL, loginConfig)
            .then(response => response.json())
            .then((json) => { 
                if(json.key)
                    dispatch(receiveLogin(username, json.key, null))
                else
                    dispatch(receiveLogin(username, '', json))
            },
            error => dispatch(receiveLogin('', '', error.toString())))
    }
}
const LOGOUT_URL = requestBaseUrl + 'rest-auth/logout/'
export const makeLogout = () => {
    const logoutConfig = {
        credentials: 'include', 
        method: 'POST',
        headers: {            
        },        
    }
    let csrftoken = Cookie.get('csrftoken')
    if (csrftoken)
        logoutConfig.headers['X-CSRFToken'] = csrftoken
    logoutConfig.headers['Authorization'] = 'Token '
    
    return function (dispatch, getState) {
        let key = getState().profile.key
        if (key)
            logoutConfig.headers['Authorization'] = `Token ${key}`
        return fetch(LOGOUT_URL, logoutConfig)
                .then(processResponse)
                .then(error => dispatch(logout(error)),
                 error => dispatch(logout(error.toString())))
    }    
}

const updateProfileUrl = requestBaseUrl + 'rest-auth/user/' 
export const updateProfile = (submitedProfile) => {
    return function (dispatch, getState) {
        let updateConfig =  {
            body: JSON.stringify(submitedProfile),
            headers: {
                "Content-Type": "application/json",
            },
            method: 'PATCH',
            credentials: 'include'
        }
        let csrftoken = Cookie.get('csrftoken')
        if (csrftoken)
            updateConfig.headers['X-CSRFToken'] = csrftoken
        let key = getState().profile.key
        if (key)
            updateConfig.headers['Authorization'] = `Token ${key}`

        return fetch(updateProfileUrl, updateConfig)
            .then(processResponse)
            .then((error) => dispatch(profileUpdated(Object.assign({}, submitedProfile, { isUpdate: true}), error)),
            error => dispatch(profileUpdated({}, error.toString())))
    }
}
export const getProfile = () => {
    return function (dispatch, getState) {
        if (getState().profile.profileFetched) {
            dispatch(profileUpdated(Object.assign({}, { isUpdate: false}), null))
            return
        }
        let updateConfig = {
            headers: {
                "Content-Type": "application/json",
            },
            credentials: 'include'
        }
        let csrftoken = Cookie.get('csrftoken')
        if (csrftoken)
            updateConfig.headers['X-CSRFToken'] = csrftoken
        let key = getState().profile.key
        if (key)
            updateConfig.headers['Authorization'] = `Token ${key}`

        return fetch(updateProfileUrl, updateConfig)
            .then(response => response.json())
            .then((json) => {
                if (json.username)
                    dispatch(profileUpdated(Object.assign({}, json, { isUpdate: false, profileFetched: true  }), null))
                else
                    dispatch(profileUpdated({}, json))
            },
                error => dispatch(profileUpdated({}, error.toString())))
    }
}
const registerUrl = requestBaseUrl + 'rest-auth/registration/' 
export const makeRegister = (submitedProfile) => {
    return function(dispatch) {
        let registerConfig =  {
            body: JSON.stringify(submitedProfile),
            headers: {
                "Content-Type": "application/json"            },
            method: 'POST',
            credentials: 'include'
        }
        return fetch(registerUrl, registerConfig)
            .then(processResponse)
            .then((error) => dispatch(registerInProcess(error)),
            error => dispatch(registerInProcess(error.toString())))
    }
}
const activateUrl = requestBaseUrl + 'rest-auth/registration/verify-email/'
export const makeActivate = (submitedProfile) => {
    return function (dispatch) {
        let activateConfig = {
            body: JSON.stringify(submitedProfile),
            headers: {
                "Content-Type": "application/json"
            },
            method: 'POST',
            credentials: 'include'
        }
        let csrftoken = Cookie.get('csrftoken')
        if (csrftoken)
            activateConfig.headers['X-CSRFToken'] = csrftoken
        return fetch(activateUrl, activateConfig)
            .then(processResponse)
            .then((error) => dispatch(activateInProcess(error)),
                error => dispatch(activateInProcess(error.toString())))
    }
}